package cn.wenhaha.app.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-03-26 15:37
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 将/static/**访问映射到classpath:/mystatic/
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/templates/");

   /*     registry.addResourceHandler("/external/**")
                .addResourceLocations("file:./static/")
                .addResourceLocations("file:./templates/");*/

        registry.addResourceHandler("/plugins/**")
                .addResourceLocations("file:./templates/plugins/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        WebMvcConfigurer.super.addCorsMappings(registry);
        registry.addMapping("/**").
                allowedOriginPatterns("*"). //允许跨域的域名，可以用*表示允许任何域名使用
                allowedMethods("*"). //允许任何方法（post、get等）
                allowedHeaders("*"). //允许任何请求头
                allowCredentials(true). //带上cookie信息
                exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内，
    }


    @Bean
    public FilterRegistrationBean<DataSourcePluginFilter> registerParam(){
        //通过FilterRegistrationBean实例设置优先级可以生效
        FilterRegistrationBean<DataSourcePluginFilter> bean = new FilterRegistrationBean<DataSourcePluginFilter>();
        bean.setFilter(new DataSourcePluginFilter());//注册自定义过滤器
        bean.setName("pluginParam");//过滤器名称
        bean.addUrlPatterns("/plugin/*");//过滤所有路径
        bean.setOrder(1);//优先级，最顶级
        return bean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new InstallAppInterceptor())
                .excludePathPatterns("/css/**.css")
                .excludePathPatterns("favicon.ico")
                .excludePathPatterns("/layui/**")
                .excludePathPatterns("/install/last")
                .excludePathPatterns("/install/restart")
                .excludePathPatterns("/install/test");




    }
}
